<?php 
class OrderAction extends GlobalAction{
	function _initialize(){			 
		 parent::_initialize();	
		 LC('@.Help.order');
		 LC('@.Lib.Json'); 
		 LC('@.Help.payment');
		 LC('@.Help.transaction');
		
	}  
		/* 未登录处理 */
    public function un_login(){	
		 
		if (empty($_SESSION['user_id'])){
			U('User/login','',true);		 
		}else{
		
		}	
	}
    //添加到购物车
	public function addtocart(){	
		$_CFG=$GLOBALS['_CFG'];
		$_LANG=L();
		$_POST['goods'] = json_str_iconv($_POST['goods']);
		//dump($_POST['goods']);
		if (!empty($_REQUEST['goods_id']) && empty($_POST['goods']))
		{
			if (!is_numeric($_REQUEST['goods_id']) || intval($_REQUEST['goods_id']) <= 0)
			{
				mdl_header("Location:./\n");
			}
			$goods_id = intval($_REQUEST['goods_id']);
			exit;
		}

		$result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
		$json  = new JSON;

		if (empty($_POST['goods']))
		{
			$result['error'] = 1;
			die($json->encode($result));
		}

		$goods = $json->decode($_POST['goods']);	
		
 		/* 商品数量是否合法 */
		if (!is_numeric($goods->number) || intval($goods->number) <= 0){
			$result['error']   = 1;
			$result['message'] = $_LANG['invalid_number'];
		}
		else
		{
			/* 添加到购物车 */
			if (addto_cart($goods->goods_id, $goods->number, $goods->spec, $goods->parent))
			{
				if ($_CFG['cart_confirm'] > 2){
					$result['message'] = '';
				}else{
					$result['message'] = $_LANG['addto_cart_success_3'];//$_CFG['cart_confirm'] == 1 ? $_LANG['addto_cart_success_1'] : $_LANG['addto_cart_success_2'];
				}
 				$result['content'] = $this->insert_cart_info();
				$result['one_step_buy'] = 1;
			}
			else
			{
				$result['message']  = G('err')->last_message();
				$result['error']    = G('err')->error_no;
				$result['goods_id'] = stripslashes($goods->goods_id);
			}
		}
		$result['confirm_type'] = !empty($_CFG['cart_confirm']) ? $_CFG['cart_confirm'] : 2;
		//dump($result);
		die($json->encode($result));
	
	
	}

		//生成库存选择;
	public function get_select_num($num,$c){
	   if($num>=10){
		$num=10;
	   }
	   $str='';
	   
	   for($i=1;$i<=$num;$i++){
		 $s=$i==$c?'selected':'';
		 $str.="<option value=".$i." $s>".$i."</option>";
	   
	   }
	   return $str;
	
	}
	public function cart(){
		 
		// dump($_SESSION);
		// exit;

		$cart_goods = get_cart_goods();
		$goods_list=$cart_goods['goods_list'];
		$glist=array();
		foreach($goods_list as $k=>$v){
			$v['select']=$this->get_select_num($v['quantity'],$v['goods_number']);
			$glist[]=$v;
		
		}
		$checkout_url = U('Order/checkout');
		if(isset($_SESSION['user_id'])){;
			if(get_last_order($_SESSION['user_id'])){
				$checkout_url = U('Order/confirm');
			}elseif($_SESSION['flow_consignee']['address_id']!=0){
				$checkout_url = U('Order/shiping');
			}

		}
		//echo $checkout_url;
		$this->assign('checkout_url', $checkout_url);
		//dump($glist);
		$this->assign('goods_list', $glist);
		$this->assign('total', $cart_goods['total']);
		$this->assign('aiqi', 1);
		$this->assign('changenumurl', U('cartcnum') );
		//购物车的描述的格式化
		$this->assign('shopping_money',         sprintf($GLOBALS['_LANG']['shopping_money'], $cart_goods['total']['goods_price']));
		$this->assign('market_price_desc',      sprintf($GLOBALS['_LANG']['than_market_price'],
			$cart_goods['total']['market_price'], $cart_goods['total']['saving'], $cart_goods['total']['save_rate']));
            //dump($cart_goods);
	    $this->display();
	}
	 
    //改变购物车的数量;
	public function cartcnum(){
        
		 $rid=getgp('rid');
		 $num=getgp('num');
		 $arr[$rid]=$num;		
		 flow_update_cart($arr);
		 
       
		$cart_goods = get_cart_goods();
		//dump($cart_goods);
		$goods_list=$cart_goods['goods_list'];
		$glist=array();
		foreach($goods_list as $k=>$v){
			$v['select']=$this->get_select_num($v['quantity'],$v['goods_number']);
			$glist[]=$v;
		
		}
		$this->assign('goods_list', $glist);
		$this->assign('total', $cart_goods['total']);
	 
		$this->assign('changenumurl', U('cartcnum') );
		//购物车的描述的格式化
		$this->assign('shopping_money',         sprintf($GLOBALS['_LANG']['shopping_money'], $cart_goods['total']['goods_price']));
		$this->assign('market_price_desc',      sprintf($GLOBALS['_LANG']['than_market_price'],
			$cart_goods['total']['market_price'], $cart_goods['total']['saving'], $cart_goods['total']['save_rate']));
        $this->display('order.cart');
		$content =ob_get_contents();
		ob_end_clean();
		$json  = new JSON;
		$result['error']   = 0;			 
		$result['message'] = $content;

		die($json->encode($result));
		 
		 //G('V')->
		//$this->show_message($_LANG['update_cart_notice'], $_LANG['back_to_cart'], 'flow.php');
		exit;
	}



	// 删除购物车中的产品;
	public function drop_cart(){
	
		/*------------------------------------------------------ */
		//-- 删除购物车中的商品
		/*------------------------------------------------------ */
		$rec_id = intval($this->getby('id'));	 
		flow_drop_cart_goods($rec_id);
		mdl_header("Location: ".U('cart')." \n");
		exit;
	
	}
	//清空购物车;
	public function clear(){
        $sql = "DELETE FROM " . gettable('cart') . " WHERE session_id='" . G('SESS_ID') . "'";
		G('db')->query($sql);
		mdl_header("Location:".U('Default/index')."\n");
	}
	//确认订单;
	public function checkout(){
		
		
		if (empty($_SESSION['user_id'])||$_SESSION['user_id']<= 0){
            U("User/login",array('back'=>('Order_checkout')),true);
			
			 //redirect($url);
        } 
		LC('@.Help.transaction');
		$order = flow_order_info();
		if($order['shipping_id']==0){
			 $e=shipping_list();			
			 $order['shipping_id']=$e[0]['shipping_id'];
		}
		if($order['pay_id']==0){
			 $e=payment_list();				 
			 $order['pay_id']=$e[0]['pay_id'];
		}
	 
        $this->assign('order', $order);
        $this->user_address();
 		$this->get_shipping_list();		  
		$this->display();
		 
	}
	//处理用户地址;
	public function user_address(){
		
       
		$_CFG=G('cfg');
	  /* 取得国家列表、商店所在国家、商店所在国家的省列表 */
        $this->assign('country_list',       get_regions());		 
        $this->assign('shop_country',       $_CFG['shop_country']);
        $this->assign('shop_province_list', get_regions(1, $_CFG['shop_country']));
         /* 获得用户所有的收货人信息 */
        if ($_SESSION['user_id'] > 0){
            $consignee_list = get_consignee_list($_SESSION['user_id']);            
        }     
		//dump($consignee_list);
        //$this->assign('name_of_region',   array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4']));
	//	$order = flow_order_info();
         //$address_id=$order['address_id'];

		$this->assign('consignee_list', $consignee_list);
	$this->assign('consignee_list_len',count($consignee_list));
	    $address=array();
	$addressid=$this->getby('addressid');
		if($addressid){
			for($i=0;$i<count($consignee_list);$i++){
		 
				  if($consignee_list[$i]['address_id']==$addressid){
				 
					 $address=$consignee_list[$i];
				  }
		
			}
		 
		         /* 取得每个收货地址的省市区列表 */
		        $province_list = array();
		        $city_list = array();
		        $district_list = array();
       
				$province_list = get_regions(1, $address['country']);
		        $city_list     = get_regions(2, $address['province']);
		        $district_list = get_regions(3, $address['city']);
		
		        $this->assign('province_list', $province_list);
		        $this->assign('city_list',     $city_list);
		        $this->assign('district_list', $district_list);
		}
		$this->assign("uadd",$address);
         /* 返回收货人页面代码 */
       // $this->assign('real_goods_count', exist_real_goods(0, $flow_type) ? 1 : 0);
		$is_show=count($consignee_list)<5?0:1;
	 
        $this->assign('is_show',$is_show);
	}
	public function get_shipping_list(){
		//ECHO 555;
		 $order = flow_order_info();
		 
		 $consignee = get_consignee($_SESSION['user_id']);
 

		/* 检查收货人信息是否完整 */
		if (!check_consignee_info($consignee))
		{
			/* 如果不完整则转向到收货人信息填写界面 */
			 //mdl_header("Location: flow.php?step=consignee\n");
		//	die('no');
			//exit;
		}
		//ECHO 333;
		$_SESSION['flow_consignee'] = $consignee;
 		 /* 取得配送列表 */
		 

		$region            = array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']);
		$shipping_list     = available_shipping_list($region);
		
		$cart_weight_price = cart_weight_price($flow_type);
		$insure_disabled   = true;
		$cod_disabled      = true;
		foreach ($shipping_list AS $key => $val)
		{
			$shipping_cfg = unserialize_config($val['configure']);
			$shipping_fee = shipping_fee($val['shipping_code'], unserialize($val['configure']),
			$cart_weight_price['weight'], $cart_weight_price['amount'], $cart_weight_price['number']);

			$shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee, false);
			$shipping_list[$key]['shipping_fee']        = $shipping_fee;
			$shipping_list[$key]['free_money']          = price_format($shipping_cfg['free_money'], false);
			$shipping_list[$key]['insure_formated']     = strpos($val['insure'], '%') === false ?
				price_format($val['insure'], false) : $val['insure'];

			/* 当前的配送方式是否支持保价 */
			if ($val['shipping_id'] == $order['shipping_id'])
			{
				$insure_disabled = ($val['insure'] == 0);
				$cod_disabled    = ($val['support_cod'] == 0);
			}
		}
	 
 		$this->assign('shipping_list',   $shipping_list);
		$this->assign('insure_disabled', $insure_disabled);
		$this->assign('cod_disabled',    $cod_disabled);
        $payment_list=$this->get_pay_list();
	    $time_list=get_time_list();
		 
		$this->assign('time_list', $time_list);

		$this->assign('payment_list', $payment_list);
       


	
	}
	//订单最终确认
	public function orderok(){
	   if (empty($_SESSION['user_id'])||$_SESSION['user_id']<= 0){
            U("User/login",array('back'=>('Order_orderok')),true);		
       } 
	   $order = flow_order_info();
	   $consignee = get_consignee($_SESSION['user_id']);
	 
	   $region            = array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']);
	   $shipping_list     = available_shipping_list($region);
      
	   $shipping_id=getgp("shipping_id");
	   $payment_id=getgp("payment_id");
	   $time_id=getgp('time_id');
	   $data=array();
	   foreach($shipping_list as $key=>$v){
	       if($v['shipping_id']== $shipping_id){		   
		       $data['shipping_name']=$v['shipping_name'];
		   }	   
	   }
	   $payment_list=$this->get_pay_list();  
	  // dump($payment_list);
	   foreach($payment_list as $key=>$v){
	       if($v['pay_id']== $payment_id){		   
		       $data['payment_name']=$v['pay_name'];
		   }	   
	   }
	   $time_list=get_time_list();
	   foreach($time_list as $key=>$v){
			   if($v['id']== $time_id){		   
				   $data['time_name']=$v['name'];
			   }	   
		}
	   $is_fapiao=getgp('is_fapiao');
	   $data['is_fapiao']=$is_fapiao==0?'不需要发票':getgp('fapiao_head');

	   $goods_not=getgp('goods_not');
       $data['goods_not']=$goods_not==0?'等待':'从订单中取消';

	   $data['postscript']=getgp('postscript');
	  //  dump($_POST);
	   $this->assign($data);
	   $this->assign('add', $consignee);
	   $_SESSION['order']=$_POST;


		$cart_goods = get_cart_goods();
		$goods_list=$cart_goods['goods_list'];
		 
		$this->assign('goods_list', $goods_list);
		 
            //dump($goods_list);


	   $this->display();
	}
	
 

    public function get_pay_list(){
	 $order = flow_order_info();
	/* 取得支付列表 */
		if ($order['shipping_id'] == 0)
		{
			$cod        = true;
			$cod_fee    = 0;
		}
		else
		{
			$shipping = shipping_info($order['shipping_id']);
			$cod = $shipping['support_cod'];

			if ($cod)
			{
				
				if ($cod)
				{
					$shipping_area_info = shipping_area_info($order['shipping_id'], $region);
					$cod_fee            = $shipping_area_info['pay_fee'];
				}
			}
			else
			{
				$cod_fee = 0;
			}
		}

		// 给货到付款的手续费加<span id>，以便改变配送的时候动态显示
		$payment_list = available_payment_list(1, $cod_fee);

		foreach ($payment_list as $key => $payment)
		{
			if ($payment['is_cod'] == '1')
			{
				$payment_list[$key]['format_pay_fee'] = '<span id="ECS_CODFEE">' . $payment['format_pay_fee'] . '</span>';
			}
			/* 如果有易宝神州行支付 如果订单金额大于300 则不显示 */
			if ($payment['pay_code'] == 'yeepayszx' && $total['amount'] > 300)
			{
				unset($payment_list[$key]);
			}
			/* 如果有余额支付 */
			if ($payment['pay_code'] == 'balance')
			{
				/* 如果未登录，不显示 */
				if ($_SESSION['user_id'] == 0)
				{
					unset($payment_list[$key]);
				}
				else
				{
					if ($_SESSION['flow_order']['pay_id'] == $payment['pay_id'])
					{
						$this->assign('disable_surplus', 1);
					}
				}
			}
		}
		return $payment_list;
	  
	}

   //提交订单;
    public function submitorder(){
			 $_LANG=L();
           
			 $_POST=array_merge($_POST, $_SESSION['flow_order']);
			 
			
			 
			 /* 取得购物类型 */
			$flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;

			/* 检查购物车中是否有商品 */
			$sql = "SELECT COUNT(*) FROM " . gettable('cart') .
				" WHERE session_id = '" . G('SESS_ID') . "' " .
				"AND parent_id = 0 AND is_gift = 0 AND rec_type = '$flow_type'";
			if (G('db')->getOne($sql) == 0)
			{
			 
				$this->show_message($_LANG['no_goods_in_cart'], '', '', 'warning');
			}
			
			/*
			 * 检查用户是否已经登录
			 * 如果用户已经登录了则检查是否有默认的收货地址
			 * 如果没有登录则跳转到登录和注册页面
			 */
          
			 
			if ( $_SESSION['user_id'] == 0){
				/* 用户没有登录且没有选定匿名购物，转向到登录页面 */
				mdl_header("Location: ".U('User/login')." \n");
				exit;
			}
		
 			$consignee = $_SESSION['flow_consignee'];
 
			/* 检查收货人信息是否完整 */
			if (!check_consignee_info($consignee, $flow_type)){
				/* 如果不完整则转向到收货人信息填写界面 */
			 
				//mdl_header("Location: ".U('User/address')." \n");
				 
			}
			
			
			$_POST['how_oos'] = isset($_POST['how_oos']) ? intval($_POST['how_oos']) : 0;
			$_POST['card_message'] = isset($_POST['card_message']) ? htmlspecialchars($_POST['card_message']) : '';
			$_POST['inv_type'] = !empty($_POST['inv_type']) ? htmlspecialchars($_POST['inv_type']) : '';
			$_POST['inv_payee'] = isset($_POST['inv_payee']) ? htmlspecialchars($_POST['inv_payee']) : '';
			$_POST['inv_content'] = isset($_POST['inv_content']) ? htmlspecialchars($_POST['inv_content']) : '';
			$_POST['postscript'] = isset($_POST['postscript']) ? htmlspecialchars($_POST['postscript']) : '';
 			$order = array(
				'shipping_id'     => intval($_POST['shipping_id']),
				'pay_id'          => intval($_POST['pay_id']),
				'pack_id'         => isset($_POST['pack']) ? intval($_POST['pack']) : 0,
				'card_id'         => isset($_POST['card']) ? intval($_POST['card']) : 0,
				'card_message'    => trim($_POST['card_message']),
				'surplus'         => isset($_POST['surplus']) ? floatval($_POST['surplus']) : 0.00,
				'integral'        => isset($_POST['integral']) ? intval($_POST['integral']) : 0,
				'bonus_id'        => isset($_POST['bonus']) ? intval($_POST['bonus']) : 0,
				'need_inv'        => empty($_POST['need_inv']) ? 0 : 1,
				'inv_type'        => $_POST['inv_type'],
				'inv_payee'       => trim($_POST['inv_payee']),
				'inv_content'     => $_POST['inv_content'],
				'postscript'      => trim($_POST['postscript']),
				'how_oos'         => isset($_LANG['oos'][$_POST['how_oos']]) ? addslashes($_LANG['oos'][$_POST['how_oos']]) : '',
				'need_insure'     => isset($_POST['need_insure']) ? intval($_POST['need_insure']) : 0,
				'user_id'         => $_SESSION['user_id'],
				'add_time'        => gmtime(),
				'order_status'    => OS_UNCONFIRMED,
				'shipping_status' => SS_UNSHIPPED,
				'pay_status'      => PS_UNPAYED,
				'agency_id'       => get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']))
				);
  			/* 扩展信息 */
			if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS)
			{
				$order['extension_code'] = $_SESSION['extension_code'];
				$order['extension_id'] = $_SESSION['extension_id'];
			}
			else
			{
				$order['extension_code'] = '';
				$order['extension_id'] = 0;
			}

			/* 检查积分余额是否合法 */
			$user_id = $_SESSION['user_id'];
			if ($user_id > 0)
			{
				$user_info = user_info($user_id);

				$order['surplus'] = min($order['surplus'], $user_info['user_money'] + $user_info['credit_line']);
				if ($order['surplus'] < 0)
				{
					$order['surplus'] = 0;
				}

				// 查询用户有多少积分
				$flow_points = flow_available_points();  // 该订单允许使用的积分
				$user_points = $user_info['pay_points']; // 用户的积分总数

				$order['integral'] = min($order['integral'], $user_points, $flow_points);
				if ($order['integral'] < 0)
				{
					$order['integral'] = 0;
				}
			}
			else
			{
				$order['surplus']  = 0;
				$order['integral'] = 0;
			}

			/* 检查红包是否存在 */
			if ($order['bonus_id'] > 0)
			{
				$bonus = bonus_info($order['bonus_id']);

				if (empty($bonus) || $bonus['user_id'] != $user_id || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type))
				{
					$order['bonus_id'] = 0;
				}
			}
			elseif (isset($_POST['bonus_sn']))
			{
				$bonus_sn = trim($_POST['bonus_sn']);
				$bonus = bonus_info(0, $bonus_sn);
				if (empty($bonus) || $bonus['user_id'] > 0 || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type))
				{
				}
				else
				{
					if ($user_id > 0)
					{
						$sql = "UPDATE " . gettable('user_bonus') . " SET user_id = '$user_id' WHERE bonus_id = '$bonus[bonus_id]' LIMIT 1";
						G('db')->query($sql);
					}
					$order['bonus_id'] = $bonus['bonus_id'];
				}
			}

 
			/* 订单中的商品 */
			$cart_goods = cart_goods($flow_type);

			if (empty($cart_goods))
			{
				$this->show_message($_LANG['no_goods_in_cart'], $_LANG['back_home'], './', 'warning');
			}

			/* 检查商品总额是否达到最低限购金额 */
			if ($flow_type == CART_GENERAL_GOODS && cart_amount(true, CART_GENERAL_GOODS) < $_CFG['min_goods_amount'])
			{
				$this->show_message(sprintf($_LANG['goods_amount_not_enough'], price_format($_CFG['min_goods_amount'], false)));
			}

			/* 收货人信息 */
			foreach ($consignee as $key => $value)
			{
				$order[$key] = addslashes($value);
			}

			/* 订单中的总额 */
			$total = order_fee($order, $cart_goods, $consignee);

			$order['bonus']        = $total['bonus'];
			$order['goods_amount'] = $total['goods_price'];
			$order['discount']     = $total['discount'];
			$order['surplus']      = $total['surplus'];
			$order['tax']          = $total['tax'];

			// 购物车中的商品能享受红包支付的总额
			$discount_amout = compute_discount_amount();
			// 红包和积分最多能支付的金额为商品总额
			$temp_amout = $order['goods_amount'] - $discount_amout;
			if ($temp_amout <= 0)
			{
				$order['bonus_id'] = 0;
			}


			/* 配送方式 */
			if ($order['shipping_id'] > 0)
			{
				$shipping = shipping_info($order['shipping_id']);
				$order['shipping_name'] = addslashes($shipping['shipping_name']);
			}
			$order['shipping_fee'] = $total['shipping_fee'];
			$order['insure_fee']   = $total['shipping_insure'];

			/* 支付方式 */
			if ($order['pay_id'] > 0)
			{
				$payment = payment_info($order['pay_id']);
				$order['pay_name'] = addslashes($payment['pay_name']);
			}
		 
			$order['pay_fee'] = $total['pay_fee'];
			$order['cod_fee'] = $total['cod_fee'];

			$order['order_amount']  = number_format($total['amount'], 2, '.', '');

			/* 如果全部使用余额支付，检查余额是否足够 */
			if ($payment['pay_code'] == 'balance' && $order['order_amount'] > 0)
			{
				if($order['surplus'] >0) //余额支付里如果输入了一个金额
				{
					$order['order_amount'] = $order['order_amount'] + $order['surplus'];
					$order['surplus'] = 0;
				}
				if ($order['order_amount'] > ($user_info['user_money'] + $user_info['credit_line']))
				{
					$this->show_message($_LANG['balance_not_enough']);
				}
				else
				{
					$order['surplus'] = $order['order_amount'];
					$order['order_amount'] = 0;
				}
			}

			/* 如果订单金额为0（使用余额或积分或红包支付），修改订单状态为已确认、已付款 */
			if ($order['order_amount'] <= 0)
			{
				$order['order_status'] = OS_CONFIRMED;
				$order['confirm_time'] = gmtime();
				$order['pay_status']   = PS_PAYED;
				$order['pay_time']     = gmtime();
				$order['order_amount'] = 0;
			}

			$order['integral_money']   = $total['integral_money'];
			$order['integral']         = $total['integral'];

			if ($order['extension_code'] == 'exchange_goods')
			{
				$order['integral_money']   = 0;
				$order['integral']         = $total['exchange_integral'];
			}

			$order['from_ad']          = !empty($_SESSION['from_ad']) ? $_SESSION['from_ad'] : '0';
			$order['referer']          = !empty($_SESSION['referer']) ? addslashes($_SESSION['referer']) : '';

			/* 记录扩展信息 */
			if ($flow_type != CART_GENERAL_GOODS)
			{
				$order['extension_code'] = $_SESSION['extension_code'];
				$order['extension_id'] = $_SESSION['extension_id'];
			}

			$affiliate = unserialize($_CFG['affiliate']);
			if(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 1)
			{
				//推荐订单分成
				$parent_id = get_affiliate();
				if($user_id == $parent_id)
				{
					$parent_id = 0;
				}
			}
			elseif(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 0)
			{
				//推荐注册分成
				$parent_id = 0;
			}
			else
			{
				//分成功能关闭
				$parent_id = 0;
			}
			$order['parent_id'] = $parent_id;

			/* 插入订单表 */
			$error_no = 0;
			do
			{
				$order['order_sn'] = get_order_sn(); //获取新订单号
				G('db')->autoExecute(gettable('order_info'), $order, 'INSERT');

				$error_no = G('db')->errno();

				if ($error_no > 0 && $error_no != 1062)
				{
					die(G('db')->errorMsg());
				}
			}
			while ($error_no == 1062); //如果是订单号重复则重新提交数据

			$new_order_id = G('db')->insert_id();
			$order['order_id'] = $new_order_id;

			/* 插入订单商品 */
			$sql = "INSERT INTO " . gettable('order_goods') . "( " .
						"order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
						"goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) ".
					" SELECT '$new_order_id', goods_id, goods_name, goods_sn, goods_number, market_price, ".
						"goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id".
					" FROM " .gettable('cart') .
					" WHERE session_id = '".G('SESS_ID')."' AND rec_type = '$flow_type'";
			G('db')->query($sql);
			/* 修改拍卖活动状态 */
			if ($order['extension_code']=='auction')
			{
				$sql = "UPDATE ". gettable('goods_activity') ." SET is_finished='2' WHERE act_id=".$order['extension_id'];
				G('db')->query($sql);
			}

			/* 处理余额、积分、红包 */
			if ($order['user_id'] > 0 && $order['surplus'] > 0)
			{
				log_account_change($order['user_id'], $order['surplus'] * (-1), 0, 0, 0, sprintf($_LANG['pay_order'], $order['order_sn']));
			}
			if ($order['user_id'] > 0 && $order['integral'] > 0)
			{
				log_account_change($order['user_id'], 0, 0, 0, $order['integral'] * (-1), sprintf($_LANG['pay_order'], $order['order_sn']));
			}


			if ($order['bonus_id'] > 0 && $temp_amout > 0)
			{
				use_bonus($order['bonus_id'], $new_order_id);
			}

			 
			/*下单后减库存*/

			 change_order_goods_stock($order['order_id'],true);
			 
  
			/* 给商家发邮件 */
			/* 增加是否给客服发送邮件选项 */
			if ($_CFG['send_service_email'] && $_CFG['service_email'] != '')
			{
				$tpl = get_mail_template('remind_of_new_order');
				$this->assign('order', $order);
				$this->assign('goods_list', $cart_goods);
				$this->assign('shop_name', $_CFG['shop_name']);
				$this->assign('send_date', date($_CFG['time_format']));
				$content = $this->fetch('str:' . $tpl['template_content']);
				send_mail($_CFG['shop_name'], $_CFG['service_email'], $tpl['template_subject'], $content, $tpl['is_html']);
			}

			/* 如果需要，发短信 */
			if ($_CFG['sms_order_placed'] == '1' && $_CFG['sms_shop_mobile'] != '')
			{
				include_once('includes/cls_sms.php');
				$sms = new sms();
				$msg = $order['pay_status'] == PS_UNPAYED ?
					$_LANG['order_placed_sms'] : $_LANG['order_placed_sms'] . '[' . $_LANG['sms_paid'] . ']';
				$sms->send($_CFG['sms_shop_mobile'], sprintf($msg, $order['consignee'], $order['tel']), 0);
			}

			/* 如果订单金额为0 处理虚拟卡 */
			if ($order['order_amount'] <= 0)
			{
				$sql = "SELECT goods_id, goods_name, goods_number AS num FROM ".
					   gettable('cart') .
						" WHERE is_real = 0 AND extension_code = 'virtual_card'".
						" AND session_id = '".SESS_ID."' AND rec_type = '$flow_type'";

				$res = G('db')->getAll($sql);

				$virtual_goods = array();
				foreach ($res AS $row)
				{
					$virtual_goods['virtual_card'][] = array('goods_id' => $row['goods_id'], 'goods_name' => $row['goods_name'], 'num' => $row['num']);
				}

				if ($virtual_goods AND $flow_type != CART_GROUP_BUY_GOODS)
				{
					/* 虚拟卡发货 */
					if (virtual_goods_ship($virtual_goods,$msg, $order['order_sn'], true))
					{
						/* 如果没有实体商品，修改发货状态，送积分和红包 */
						$sql = "SELECT COUNT(*)" .
								" FROM " . $ecs->table('order_goods') .
								" WHERE order_id = '$order[order_id]' " .
								" AND is_real = 1";
						if (G('db')->getOne($sql) <= 0)
						{
							/* 修改订单状态 */
							update_order($order['order_id'], array('shipping_status' => SS_SHIPPED, 'shipping_time' => gmtime()));

							/* 如果订单用户不为空，计算积分，并发给用户；发红包 */
							if ($order['user_id'] > 0)
							{
								/* 取得用户信息 */
								$user = user_info($order['user_id']);

								/* 计算并发放积分 */
								$integral = integral_to_give($order);
								log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($_LANG['order_gift_integral'], $order['order_sn']));

								/* 发放红包 */
								send_order_bonus($order['order_id']);
							}
						}
					}
				}

			}
			 clear_cart();
			/* 清空购物车 */
			// clear_cart($flow_type);
			/* 清除缓存，否则买了商品，但是前台页面读取缓存，商品数量不减少 */
			clear_cache_files();

			/* 插入支付日志 */
			$order['log_id'] = insert_pay_log($new_order_id, $order['order_amount'], PAY_ORDER);
 			/* 取得支付信息，生成支付代码 */
			if ($order['order_amount'] > 0)
			{
				$payment = payment_info($order['pay_id']);
				 

				include_once(MANAGEPATH.'/Modules/payment/' . $payment['pay_code'] . '.php');
				 
				$pay_obj    = new $payment['pay_code'];
 
				$pay_online = $pay_obj->get_code($order, unserialize_config($payment['pay_config']));


				$order['pay_desc'] = $payment['pay_desc'];
				 

				$this->assign('pay_online', $pay_online);
			}
			//dump($GLOBALS['_LANG']);
			 
			if(!empty($order['shipping_name']))
			{
				$order['shipping_name']=trim(stripcslashes($order['shipping_name']));
			}

			/* 订单信息 */
			$this->assign('order',      $order);
			$this->assign('total',      $total);
			$this->assign('goods_list', $cart_goods);
			$this->assign('order_submit_back', sprintf($_LANG['order_submit_back'], $_LANG['back_home'], $_LANG['goto_user_center'])); // 返回提示

			//user_uc_call('add_feed', array($order['order_id'], BUY_GOODS)); //推送feed到uc
			unset($_SESSION['flow_consignee']); // 清除session中保存的收货人信息
			unset($_SESSION['flow_order']);
			unset($_SESSION['direct_shopping']);
//dump($this->view->vars);
			$this->display();
	}

    //删除地址;
	public function deluaddress(){
		 LC('@.Help.transaction');
		 LL('user');
		$this->un_login();
	    $_LANG=L();
		$consignee_id = intval($this->getby('id'));
		//echo $consignee_id;
		if (drop_consignee($consignee_id)){
			mdl_header("Location: ".U('Order/checkout')."\n");
			exit;
		}
		else
		{
			$this->show_message($_LANG['del_address_false']);
		}
	
	}
    //保存送货地址;
	public function saveaddress(){
		 
		LC('@.Help.transaction');
	 
		$add=$_POST;
		
		$consignee = array(
					'default' => 1,
					'user_id' => $_SESSION['user_id'],
					'address_id'    => empty($add['address_id']) ? 0  : intval($add['address_id']),
					'consignee'     => empty($add['consignee'])  ? '' : trim($add['consignee']),
					'country'       => empty($add['country'])    ? '' : $add['country'],
					'province'      => empty($add['province'])   ? '' : $add['province'],
					'city'          => empty($add['city'])       ? '' : $add['city'],
					'district'      => empty($add['district'])   ? '' : $add['district'],
					'email'         => empty($add['email'])      ? '' : $add['email'],
					'address'       => empty($add['address'])    ? '' : $add['address'],
					'zipcode'       => empty($add['zipcode'])    ? '' : make_semiangle(trim($add['zipcode'])),
					'tel'           => empty($add['tel'])        ? '' : make_semiangle(trim($add['tel'])),
					//'mobile'        => empty($add['mobile'])     ? '' : make_semiangle(trim($add['mobile'])),
					'sign_building' => empty($add['sign_building']) ? '' : $add['sign_building'],
					'best_time'     => empty($add['best_time'])  ? '' : $add['best_time'],
				);
				        	update_address($consignee);
		$address_id=$consignee['address_id'];	
		// echo  $consignee['address_id'] ;
		// exit;
		 mdl_header('Location: '.U('Order/shiping',array('addressid'=>$address_id)).'');
			exit;
	}
    //获取地址;
public function getaddress(){
		if(!is_array($_SESSION['flow_consignee'])||($this->getby("addressid"))){
			$order = flow_order_info();
			$myaddress=get_one_consignee($order['address_id']);
			$_SESSION['flow_consignee']=$myaddress;
		}else{
			$myaddress=$_SESSION['flow_consignee'];
		}
       
		$this->assign('myaddress', $myaddress);
	
	}

	//选择配送方式;
	public function  shiping(){
		$address_id=$this->getby("addressid");
	if(!$address_id){
			$sql='select address_id from '.gettable('users').' where user_id = '.$_SESSION['user_id'];
			$res=G('db')->getRow($sql);
			$address_id=$res['address_id'];
		}
		 
		$order = flow_order_info();	
		if(!empty($address_id)){
			$order['address_id']=$address_id;
		}		 
		$this->assign('shipping_list', get_myship_list());
		 
		$_SESSION['flow_order']=$order;
		//dump($_SESSION['flow_order']);
		$this->getaddress();
		$this->display();
	
	} 
	//选择支付方式;
	public function payment(){	
	
		$order = flow_order_info();
		
		$this->getaddress();
		$shipping_id=getgp("shipping_id");		 			
		$order['shipping_id']=$shipping_id;	 
		$order['shipinfo']=get_one_myship($order['shipping_id']);
		$order['payment_list']=payment_list();
		if($order['pay_id']==0){
		     $order['pay_id']=$order['payment_list'][0]['pay_id'];
		}
		$this->assign($order);	 
		$_SESSION['flow_order']=$order;	  
		$this->display();
	
	
	}
	//选择时间;
	public function orderday(){	 

		$order = flow_order_info();
	 
		$pay_id=$_POST['payment_id'];
		if($pay_id){
		$order['pay_id']=$pay_id;
		}	 			
	
		 
		$this->getaddress();
 
        $order['payinfo']=payment_info($order['pay_id']);
		$order['orderday']=get_time_list(); 			
		 	
		$_SESSION['flow_order']=$order;
		$this->assign($order);			 	
		$this->display();
	}
	//确认订单;
	public function confirm(){
	 /* 取得购物类型 */
	$flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;
		$cart_goods = cart_goods($flow_type);
		$order = flow_order_info();
		if(!is_array($_SESSION['flow_consignee'])){
			$_SESSION['flow_consignee']=get_last_order($_SESSION['user_id']);
		}
		$this->getaddress();
		$payinfo=payment_info($order['pay_id']);	
	 
        	$this->assign('payinfo', $payinfo);	

		$day_id=getgp("day_id");		 
		$order['day_id']=$day_id;
		if($day_id){
			$order['day_id']=$day_id;	
			$_SESSION['flow_consignee']['best_time']=$day_id;
		}else{
			$order['day_id']=$_SESSION['flow_consignee']['best_time'];
		}

		/*费用合计*/
		$total = order_fee($order, $cart_goods, $_SESSION['flow_consignee']);
		$amount=array();
		$amount['goods_price']=$total['goods_price_formated'];
		$amount['market_price']=$total['market_price_formated'];
		$amount['saving']=$total['saving_formated'];
		$amount['save_rate']=$total['save_rate'];
		unset($total);

		$this->assign('amount', $amount);

		$orderday=get_one_time($order['day_id']); 
	 	
		$flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;

		$cart_goods = cart_goods($flow_type); // 取得商品列表，计算合计

		$consignee = get_consignee($_SESSION['user_id']);
		 
		$total = order_fee($order, $cart_goods, $consignee);

			  /* 如果使用红包，取得用户可以使用的红包及用户选择的红包 */
		 
			// 取得用户可用红包
			 
			$user_bonus = user_bonus($_SESSION['user_id'], $total['goods_price']);
			if (!empty($user_bonus))
			{
				foreach ($user_bonus AS $key => $val)
				{
					$user_bonus[$key]['bonus_money_formated'] = price_format($val['type_money'], false);
				}
						//dump($user_bonus);
				$this->assign('bonus_list', $user_bonus);
			}
         
			// 能使用红包
			$this->assign('allow_use_bonus', 1);
		 
		
		$_SESSION['flow_order']=$order;
		$this->assign('order', $order);	
		$this->assign('orderday', $orderday);
		
		$cart_goods = get_cart_goods();
		$goods_list=$cart_goods['goods_list'];
		 
		$this->assign('goods_list', $goods_list);
		 
	 
	    ///$this->assign('total',$total);
		 $content=$this->view->getfetch('order_total');
		 
        //$this->assign('goods_total',$content);
		$this->display();
	
	}
	/* 验证红包序列号 */
   public function  validate_bonus(){
		$bonus_sn = trim($_REQUEST['bonus_sn']);
		$bonus = bonus_info(0, $bonus_sn);

	//    if (empty($bonus) || $bonus['user_id'] > 0 || $bonus['order_id'] > 0)
	//    {
	//        die($_LANG['bonus_sn_error']);
	//    }
	//    if ($bonus['min_goods_amount'] > cart_amount())
	//    {
	//        die(sprintf($_LANG['bonus_min_amount_error'], price_format($bonus['min_goods_amount'], false)));
	//    }
	//    die(sprintf($_LANG['bonus_is_ok'], price_format($bonus['type_money'], false)));
		$bonus_kill = price_format($bonus['type_money'], false);

	
		$result = array('error' => '', 'content' => '');

		/* 取得购物类型 */
		$flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;

		/* 获得收货人信息 */
		$consignee = get_consignee($_SESSION['user_id']);

		/* 对商品信息赋值 */
		$cart_goods = cart_goods($flow_type); // 取得商品列表，计算合计

		if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type))
		{
			$result['error'] = $_LANG['no_goods_in_cart'];
		}
		else
		{
			/* 取得购物流程设置 */
			$this->assign('config', $_CFG);

			/* 取得订单信息 */
			$order = flow_order_info();

			if ((!empty($bonus) && $bonus['user_id'] == $_SESSION['user_id']) || $bonus_kill == 0)
			{
				$order['bonus_kill'] = $bonus['type_money'];
			}
			else
			{
				$order['bonus_kill'] = 0;
				$result['error'] = $_LANG['invalid_bonus'];
			}
	//print_r($order);
			/* 计算订单的费用 */
			$total = order_fee($order, $cart_goods, $consignee);
	//print_r($total);
			$this->assign('total', $total);

			/* 团购标志 */
			if ($flow_type == CART_GROUP_BUY_GOODS)
			{
				$smarty->assign('is_group_buy', 1);
			}

			 
			$result['content'] = $this->view->getfetch('order_total');
		}

		$json = new JSON();
		die($json->encode($result));


	}
}
?>